<template>
  <div>
    <wheel
      :num="wheelNum"
      :win-num="winNum"
      ref="wheel"
      @start-click="wheelStartClick"
      @rotate-end="wheelRorateEnd"
    />
    <share-tips-modal :visible="tipsVisible" @close-modal="closeTipsModal" />
    <prize-result-modal
      :visible="resultVisible"
      :content="resultContent"
      :is-prize="resultIsPrize"
      @close-modal="closeResultModal"
    />
  </div>
</template>

<script>
import Wheel from "@/components/wheel/components/luckywheel";
import { prizeList } from "@/config/prizeConfig";
import { Dialog, Toast, Popup } from "vant";
import { mapMutations, mapActions } from "vuex";
import { aid } from "@/config/shareConfig";
import { randomNum, isSameDay, formatDate } from "@/js/utils";
import ShareTipsModal from "@/components/shareTipsModal";
import PrizeResultModal from "@/components/prizeResultModal";

let isPrizeList = [];
let notPrizeList = [];
prizeList.forEach((e) => {
  if (e.isPrize) {
    isPrizeList.push(e);
  } else {
    notPrizeList.push(e);
  }
});
const PrizeProbability = 0.0001; //中奖概率
const EverydayNum = 3; //每天抽奖次数
const EverydayDefNum = 0; //默认0次
export default {
  components: {
    Wheel,
    ShareTipsModal,
    PrizeResultModal,
    [Popup.name]: Popup,
  },
  data() {
    return {
      winNum: -1,
      canClick: false,
      tipsVisible: false,
      resultVisible: false,
      resultContent: "",
      resultIsPrize: false,
    };
  },
  computed: {
    wheelNum() {
      return this.$store.state.activity.drawNum;
    },
    appData() {
      return this.$store.state.appData;
    },
    enrollMsg() {
      return this.$store.state.activity.enrollMsg;
    },
  },
  watch: {
    appData: {
      deep: true,
      immediate: true,
      handler(val, oldVal) {
        if (val && val.resQuery && val.jsApiTicket && val.resQuery.code) {
          this.canClick = true;
          this.initData(val.resQuery, val.jsApiTicket);
        }
      },
    },
  },
  mounted() {},
  methods: {
    ...mapActions({
      addLottery: "activity/addLottery",
      queryLotteryWinner: "activity/queryLotteryWinner",
      queryIsLottery: "activity/queryIsLottery",
    }),
    ...mapMutations({
      setDrawNum: "activity/setDrawNum",
      setIsClickShareTrue: "activity/setIsClickShareTrue",
      setWinnerRecord: "activity/setWinnerRecord",
      setDrawRecord: "activity/setDrawRecord",
      setDrawPrizeMsg: "activity/setDrawPrizeMsg",
    }),
    async initData() {
      let isPrizeRes = await this.queryIsLottery({
        ac_id: aid,
        open_id: this.$store.state.userInfo.openId,
      });
      console.log("isPrizeRes", isPrizeRes);
      if (isPrizeRes && isPrizeRes.code == 0) {
        if (Array.isArray(isPrizeRes.data) && isPrizeRes.data.length == 0) {
          //没中奖记录
          this.setDrawNum(EverydayNum);
          this.setDrawRecord([]);
        } else {
          //有中奖记录
          let todayNum = EverydayNum;
          let curDate = new Date();
          isPrizeRes.data.forEach((e) => {
            if (isSameDay(curDate, e.createTime.replace(/\-/g, "/"))) {
              todayNum = todayNum - 1;
            }
          });
          if (todayNum > 0) {
            this.setDrawNum(todayNum);
          } else {
            this.setDrawNum(EverydayDefNum);
          }
          this.setDrawRecord(isPrizeRes.data);
        }

        console.log("次数", this.wheelNum);
      }
    },
    getWinnerRecord() {
      //获取总中奖列表
      return new Promise((resolve, reject) => {
        this.queryLotteryWinner({
          ac_id: aid,
        })
          .then((res) => {
            console.log(res);
            if (res && res.code == 0) {
              if (Array.isArray(res.data)) {
                let arr = [];
                res.data.forEach((e) => {
                  try {
                    e.prize = JSON.parse(e.prize);
                  } catch (error) {
                    console.log(err);
                  }
                });
                this.setWinnerRecord(res.data);
                resolve();
              }
            }
            reject();
          })
          .catch((err) => {
            console.log(err);
            reject();
          });
      });
    },
    createLottery() {
      //生成本次中奖
      return new Promise((resolve, reject) => {
        let randomNum1 = Math.random();
        let result = {};
        console.log(randomNum1);
        if (randomNum1 < PrizeProbability) {
          //万分之一
          this.getWinnerRecord()
            .then(() => {
              let record = this.$store.state.activity.winnerRecord;
              let isPrizeCountObj = {};
              let idList = [];
              isPrizeList.forEach((e) => {
                isPrizeCountObj[e.id] = e.total;
                idList.push(e.id);
              });
              record.forEach((e) => {
                if (idList.some((e1) => e1 == e.prize.id) && e.prize.isPrize) {
                  isPrizeCountObj[e.prize.id] = isPrizeCountObj[e.prize.id] - 1;
                }
              });
              let flag = true;
              console.log("isPrizeCountObj", isPrizeCountObj);
              let isNullPrize = 0;
              Object.keys(isPrizeCountObj).forEach((key) => {
                isNullPrize += isPrizeCountObj[key];
              });
              console.log("isNullPrize", isNullPrize);
              if (isNullPrize == 0) {
                let indexNum = randomNum(0, 2);
                result = notPrizeList[indexNum];
              } else {
                while (flag) {
                  let indexNum = randomNum(0, 2);
                  console.log("大奖index", indexNum);
                  if (isPrizeCountObj[isPrizeList[indexNum].id]) {
                    result = isPrizeList[indexNum];
                    flag = false;
                  }
                }
              }

              resolve({ ...result });
            })
            .catch((err) => {
              reject(err);
            });
        } else {
          let indexNum = randomNum(0, 2);
          result = notPrizeList[indexNum];
          resolve({ ...result });
        }
      });
    },
    showShareModalOrNot() {
      return new Promise((resolve, reject) => {
        console.log(this.$store.state.activity.isClickShare);
        if (this.$store.state.activity.isClickShare) {
          resolve(true);
        } else {
          //打开引导弹窗
          this.tipsVisible = true;
          this.setIsClickShareTrue();
          resolve(false);
        }
      });
    },
    async wheelStartClick() {
      if (this.wheelNum == 0) {
        return Dialog.confirm({
          message: `今日抽奖次数已用完，请明天分享后再来~`,
          showCancelButton: false,
        }).then(() => {
          // on confirm
        });
      }
      let showModal = await this.showShareModalOrNot();
      if (this.canClick && showModal) {
        Toast.loading();
        this.createLottery()
          .then((res) => {
            console.log(res);
            this.winNum = res.index;
            this.setDrawPrizeMsg(res);
            this.setDrawNum(this.wheelNum - 1);
            Toast.clear();
            this.$nextTick(() => {
              this.$refs.wheel.rotating();
            });
            return this.addLottery({
              open_id: this.$store.state.userInfo.openId,
              win_or_not: res.isPrize,
              prize: JSON.stringify(res),
              ac_id: aid,
            });
          })
          .then((res) => {
            console.log(res);
            this.queryIsLottery({
              ac_id: aid,
              open_id: this.$store.state.userInfo.openId,
            }).then((res) => {});
          })
          .catch((err) => {
            console.log(err);
            Toast.clear();
          });
      }
    },
    wheelRorateEnd(prize) {
      let resultContent = "";
      if (prize.isPrize) {
        resultContent = this.enrollMsg
          ? `恭喜您获得&nbsp;<span class="colorRed">${prize.name}</span>`
          : `恭喜您获得&nbsp;<span class="colorRed">${prize.name}</span>，请前往填写收货信息~`;
        this.resultIsPrize = true;
      } else {
        resultContent = "很遗憾没有中奖，谢谢参与~";
        this.resultIsPrize = false;
      }

      this.resultContent = resultContent;
      this.$nextTick(() => {
        this.resultVisible = true;
      });
    },
    closeTipsModal() {
      this.tipsVisible = false;
    },
    closeResultModal() {
      this.resultVisible = false;
    },
  },
};
</script>

<style lang="scss">
</style>